<?php 

namespace Weixin\Controller;
use Common\Controller\WeixinBase;
use Common\Model\Model;

class WorkController extends WeixinbaseController
{
    /**
     * 食谱列表
     */
    public function index()
    {
        $cateid = I('get.cateid');
        if(!intval($cateid))
        {
            header('Location:'.WEB_URL.'/weixin/index/category');
            exit;
        }
        $this->assign('cateid', $cateid);
        
        $catetype = I('get.type');
        $catetype = intval($catetype) == 0 ? 0 : 1;
        
        $work = D('Weixin/Works');
        $borCate = $work->getBorCate($cateid, $catetype);
        
        foreach($borCate as $fk => $fv)
        {
            foreach($fv as $sk => $sv)
            {
                if($cateid == $sv['cateid'])
                {
                    $catename = $sv['catename'];
                    
                    
                    $borCate[$fk][$sk]['is_active'] = 1;
                   
                    
                    $this->assign('catename', $catename);
                }
                if($sv['parentid'] == 1)
                {
                    $tempCate = M('Category')->where(array('parentid' => $sv['cateid'], 'status' => 1))->order('sort desc, cateid asc')->limit(1)->field('cateid')->find();
                    if($tempCate['cateid'])
                    {
                        $borCate[$fk][$sk]['cateid'] = $tempCate['cateid'];
                          
                    }
                }
            }
        }
        $this->assign('borCate', $borCate);
        
        $childCateid = $work->getChlidCateid($cateid);
        
        $count = M('Works')->where('cateid IN('.$childCateid.') and type=1 and status=1')->count();
        $page = $this->Pages($count, 5);
        $list = $work->getWorkList($childCateid, '', $page->firstRow, $page->listRows);
        if($_GET['code'] == 'getPage')
        {
            if(count($list) > 0)
            {
                $this->success($list);
            }
            $this->error('fail');
        }
        $this->assign('list', $list);
        $this->display();
    }
    
    /**
     * 搜索
     */
    public function search()
    {
        $title = I('get.title');
        if($title)
        {
            $where = " and title like '%".$title."%' ";
        }
        $this->assign('title', $title);
        $count = M('Works')->where("status=1".$where)->count();
        $page = $this->Pages($count, 6);
        $list = D('Weixin/Works')->getWorkList(0, $title, $page->firstRow, $page->listRows);
        
        if($_GET['code'] == 'getPage')
        {
            if(count($list) > 0)
            {
                $this->success($list);
            }
            $this->error('fail');
        }
        $this->assign('list', $list);
        $this->display();
    }
    
    /**
     * 食谱动态
     */
    public function dynamic()
    {
        $type = I('get.type');
        $type = empty($type) ? 'default' : $type;
        $this->assign('type', $type);
        $order = 'create_time desc';
        if($type == 'new')
        {
            $order = 'create_time desc';
        }
        elseif($type == 'hot')
        {
            $order = 'clicknum desc';
        }
        elseif($type == 'coll')
        {
            $order = 'favoritenum desc';
        } 
        $count = M('Works')->where("status=1 and type=1")->count();
        $page = $this->Pages($count, 10);
        $list = D('Weixin/Works')->getDynamic($order, $page->firstRow, $page->listRows);
        if($_GET['code'] == 'getPage')
        {
            if(count($list) > 0)
            {
                $this->success($list);
            }
            $this->error('fail');
        }
        $this->assign('pageType', 'dynamic');
        $this->assign('list', $list);
        $this->display();
    }
    
    /**
     * 食谱详情
     */
    public function detail()
    {
        $workid = I('get.workid');
        if(!intval($workid))
        {
            header('Location:'.WEB_URL.U('Index/category'));
            exit;
        }
        $works = M('Works');
        $works->where(array('workid' => $workid))->setInc('clicknum');
        $detail=D('Works')->relation(true)->find($workid);
        if(!$detail){
            header('Location:'.WEB_URL.U('Index/category'));
            exit;
        }

        $yf_thumb = array();
        $yf_pic = array();
        if(!empty($detail['all_pic']))
        {
            $yf_arr = json_decode($detail['all_pic'], true);
            $yf_temp = array();
            foreach($yf_arr as $k => $v)
            {
                $yf_thumb[] = WEB_URL.$v;
                $yf_ex = explode("/", $v);
                $yf_ex[count($yf_ex)-1] = str_replace("yf_", "", $yf_ex[count($yf_ex)-1]);
                $yf_pic[] = WEB_URL.implode("/", $yf_ex);
            }
        }
        else
        {
            $yf_arr = array();
            $yf_thumb[] = $yf_pic[] = WEB_URL.$detail['image'];
        }
        $stepPic = array();
        foreach($detail['works_makestep'] as $mk => $mv)
        {
            $detail['works_makestep'][$mk]['num'] = $mk + 1;
            $stepPic[] = $detail['works_makestep'][$mk]['simage'] = WEB_URL.$mv['simage'];
        }
        $stepPic = implode(',', $stepPic);
        $this->assign('stepPic', $stepPic);
        
        $detail['create_time'] = format_time($detail['create_time'], 'Y-m-d H:i');
        $detail['image'] = WEB_URL.$detail['image'];
        $detail['thumb'] = implode(",", $yf_thumb);
        $detail['pic'] = implode(",", $yf_pic);
        $detail['WorksMaterials_count'] = count($detail['WorksMaterials']);
        $detail['title'] = hy_substr(trim($detail['title']), 9);
        $this->assign('detail', $detail);
        
        $userInfo = M('User')->where(array('userid' => $detail['userid']))->field('nickname, uavatar, ifrz')->find();
        $this->assign('userInfo', $userInfo); 

        $copyNum = $works->where(array('copyid' => $workid, 'status' => 1))->count();
        $this->assign('copyNum', $copyNum);
        $copyInfo = M()
        ->table(array(C('DB_PREFIX').'works' => 'W', C('DB_PREFIX').'user' => 'U'))
        ->where('W.copyid='.$workid." and W.status=1 and W.userid=U.userid")
        ->order('W.create_time desc')
        ->field('W.workid, W.content, W.image, U.nickname, U.uavatar')
        ->limit(12)
        ->select();
        
//         echo "<pre>";
//         print_r(array_chunk($copyInfo, 3));
        
//         foreach ($copyInfo as $k => $v)
//         {
            
//         }
        
        $this->assign('copyInfo', array_chunk($copyInfo, 3));
        
        $where['infoid']=$workid;
        $where['type']=1;
        $where['parent_id'] = 0;
        $count = M('UserMessage')->where($where)->count();
        // $limitRows = 5; // 设置每页记录数
        $limitRows = C('YF_PAGE');
        $page = $this->ajaxpage($count,$limitRows,'#msg','ajax_div','ajax_page_div');
        
        $Model=new Model();
        $message=$Model
        ->table(array(
            C('DB_PREFIX').'user_message'=>'M',
            C('DB_PREFIX').'user'=>'U',
        )
        )
        ->where('M.userid=U.userid and M.status=true and M.infoid='.$workid.' and M.type=1 and M.parent_id=0')//yf 0912
        ->field('M.create_time,M.content,U.nickname,U.uavatar,U.openuid,U.uprovince,U.ucity,U.userid,M.id,M.touserid,U.ifrz')
        ->order('M.create_time DESC')
        ->limit($page->firstRow . ',' . $page->listRows)
        ->select();
        
        foreach($message as $k=>$v){
            $child_temp = array();
            $child_temp = $Model->table(C('DB_PREFIX').'user_message')->field('*')->where(array('parent_id' => $v['id']))->order('create_time ASC')->select();
        
            $message[$k]['childlist'] = array();
            if($child_temp)
            {
                foreach($child_temp as $yk => $yv)
                {
                    if($yv['userid'] == 0)
                    {
                        $child_temp[$yk]['nickname'] = "烘焙圈";
                        $child_temp[$yk]['openuid'] = 0;
                    }
                    else
                    {
                        $yf_user = array();
                        $yf_user = M('User')->field('openuid, nickname, uprovince, ucity, uavatar, ifrz')->where(array('userid'=>$yv['userid']))->find();
                        $child_temp[$yk]['nickname'] = $yf_user['nickname'];
                        $child_temp[$yk]['openuid'] = $yf_user['openuid'];
                        $child_temp[$yk]['uprovince'] = $yf_user['uprovince'];
                        $child_temp[$yk]['ucity'] = $yf_user['ucity'];
                        $child_temp[$yk]['uavatar'] = $yf_user['uavatar'];
                        $child_temp[$yk]['ifrz'] = $yf_user['ifrz'];
                    }
                    if($yv['touserid'] != 0)
                    {
                        $child_temp[$yk]['touser'] = M('User')->field('openuid,nickname')->where(array('userid'=>$yv['touserid']))->find();
                    }
                    else
                    {
                        $child_temp[$yk]['touser']['nickname'] = "烘焙圈";
                        $child_temp[$yk]['touser']['openuid'] = 0;
                    }
                }
                $message[$k]['childlist'] = $child_temp;
            }
            $message[$k]['tempname'] = hy_substr($v['nickname'], 4, true);
            //$message[$k]['tempname'] = $v['nickname'];
            $message[$k]['touser'] = array();
            if(!empty($v['touserid']))
            {
                $message[$k]['touser']=M('User')->field('openuid,nickname')->where(array('userid'=>$v['touserid']))->find();
            }
        }
        $this->assign('type', 1);
        $this->assign('msglist', $message);
        
        $del = 0;
        if($this->userid)
        {
            if($this->userid != $detail['userid'])
            {
                $fans = M('UserFans')->where(array('myid' => $this->userid, 'userid' => $detail['userid'], 'status' => 1))->count();
                $this->assign('fans', $fans);
                $dig = M('Dig')->where(array('userid' => $this->userid, 'status' => 1, 'type' => 1, 'infoid' => $workid))->count();
                $this->assign('dig', $dig);
                $coll = M('UserFavorite')->where(array('userid' => $this->userid, 'status' => 1, 'type' => 1, 'infoid' => $workid))->count();
                $this->assign('coll', $coll);
                $is_del = 0;
            }
            else 
            {
                $is_del = 1;
            }            
        }
        $this->assign('is_del', $is_del);
        $share['shareUrl'] = WEB_URL.$_SERVER['REQUEST_URI'];
        $share['shareTitle'] = $detail['title'];
        $share['sharePic'] = WEB_URL.$detail['image'];
        $share['shareDesc'] = hy_substr($detail['content'], 30);
        $this->assign('share', $share);
        $this->getJsdk();
        
        $this->assign('userid', $this->userid);
        
        $this->display();
    }
    
    /**
     * 添加食谱
     */
    public function add()
    {
//         $this->success("添加成功！", U('User/index',array("type"=>1)));
        if($_POST)
        {
            $cateid = intval($_POST['cateid']);
            $post=$_POST;
            $post['title'] = trim($post['title']);
            if(count($post['all_pic']) > 0)
            {
                $arr = $this->getPic($_POST['all_pic']);
            }
            else
            {
                $this->error('请上传至少一张作品图');
            }
            $post['image'] = $arr['image'];
            $post['all_pic'] = json_encode($arr['thumb']);
            
            if(empty($post['simage'][0]) || empty($post['scontent'][0])){
                $this->error('请至少填写一项食谱操作步骤');
                return false;
            }
            
            //yf start
            foreach($post['simage'] as $kk => $vv)
            {
                if(empty($vv) && empty($post['scontent'][$kk]))
                {
                    unset($post['simage'][$kk]);
                    unset($post['scontent'][$kk]);
                }
                elseif(empty($vv) || empty($post['scontent'][$kk]))
                {
                    //$this->error('请补全步骤图或者是步骤描述');
                    //return false;
                }
                else 
                {
                    $arr = $this->getPic(array(0 => $vv), 300, 200);
                    $post['simage'][$kk] = $arr['image'];
                }
            }
            
            $post['type'] = 1;
            $post['userid'] = $this->userid;
            
            //获取当前栏目配置
            $category = getCategory($cateid);
            $model = D('Weixin/Works');
            if($category['child'] == 0) 
            {
                $status = $model->addModel($post);
                if($status) 
                {
                    $this->success("添加成功！", U('User/index',array("type"=>1)));
                } 
                else 
                {
                    $error = $model->getError();
                    $this->error($error ? $error : '添加失败！');
                }
            } 
            else 
            {
                $this->error("该栏目类型无法发布！");
            }
        }
        $this->isLogin();
        $this->getJsdk();
        $category = D('Weixin/Index')->getCategory(1, false);
        $this->assign('category', $category);
        $this->display();
    }
    
    /**
     * 获取分类
     */
    public function getCategory()
    {
        $parentid = I('get.parentid');
        if($parentid == 0 || empty($parentid))
        {
            $this->error('参数错误');
        }
        $category = D('Weixin/Index')->getCategory($parentid, false);
        if(count($category) > 0)
        {
            $this->success($category);
        }
        $this->error('该分类还未添加二级分类');
    }
    
    /**
     * 删除作品
     */
    public function delworks(){
        $workid = I('get.workid');
        if(empty($workid)){
            $this->error('删除出错,请稍候再试!');
        }
        $worksModel=M('Works');
        $workuserid=$worksModel->where(array('workid'=>$workid))->getField('userid');
        if($this->userid!=$workuserid){
            $this->error('您无权限删除该食谱!');
        }
        $model=D('Weixin/Works');
        if($model->deleteWorks($workid)){
            $this->success('成功删除该食谱!', U('User/index'));
        }else{
            $error=$model->getError();
            $this->error($error ? $error : '删除食谱失败!');
        }
    }
    
}
